<template>
  <div class="app-container">
    <!-- 搜索 -->
    <div class="block">
      工号：
      <el-input v-model.trim="userQuery.example.workerNum"
                placeholder="请输入工号搜索"
                style="width: 200px;"
                class="filter-item"
                @keyup.enter.native="fetchUser" />
      用户名：
      <el-input v-model.trim="userQuery.example.username"
                placeholder="请输入用户名搜索"
                style="width: 200px;"
                class="filter-item"
                @keyup.enter.native="fetchUser" />
      <el-button class="filter-item"
                 type="primary"
                 icon="el-icon-search"
                 round
                 @click="fetchUser">
        搜索
      </el-button>
      <el-button class="filter-item"
                 style="margin-left: 10px;"
                 type="primary"
                 icon="el-icon-refresh-left"
                 round
                 @click="reset">
        重置
      </el-button>
    </div>
    <!-- 统一操作 -->
    <div class="block">
      <el-button class="filter-item"
                 style="margin-left: 10px;"
                 type="primary"
                 icon="el-icon-plus"
                 round
                 @click="showDialog(null)">
        添加
      </el-button>
    </div>
    <el-table v-loading="listLoading"
              ref="userList"
              :data="userList"
              element-loading-text="正在获取用户数据..."
              border
              fit
              max-height="630"
              highlight-current-row>
      <el-table-column type="selection"
                       width="50">
      </el-table-column>
      <el-table-column align="center"
                       label="id"
                       sortable
                       prop="id"
                       width="60">
        <template slot-scope="{row}">
          {{ row.id }}
        </template>
      </el-table-column>
      <el-table-column align="center"
                       prop="workerNum"
                       sortable
                       label="工号">
        <template slot-scope="{row}">
          {{ row.workerNum }}
        </template>
      </el-table-column>
      <el-table-column label="用户名"
                       align="center">
        <template slot-scope="{row}">
          {{ row.username }}
        </template>
      </el-table-column>
      <el-table-column label="用户角色"
                       align="center">
        <template slot-scope="{row}">
          <span v-for="id in row.roleIds"
                :key="id">
            {{ getRoleName(id) }},
          </span>
        </template>
      </el-table-column>
      <el-table-column label="性别"
                       align="center">
        <template slot-scope="{row}">
          {{ row.sex|sexFilter }}
        </template>
      </el-table-column>
      <el-table-column label="所属公司"
                       align="center">
        <template slot-scope="{row}">
          {{ row.companyId | companyFilter}}
        </template>
      </el-table-column>
      <el-table-column label="所属部门"
                       align="center">
        <template slot-scope="{row}">
          {{ row.departmentId | depFilter }}
        </template>
      </el-table-column>
      <el-table-column label="职位"
                       align="center">
        <template slot-scope="{row}">
          {{ row.positionId | posFilter}}
        </template>
      </el-table-column>
      <el-table-column class-name="state-col"
                       label="状态"
                       align="center">
        <template slot-scope="{row}">
          <el-tag :type="row.state | stateTagFilter">{{ row.state | userStateFilter }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center"
                       width="250"
                       label="操作">
        <template slot-scope="{row}">
          <el-button type="primary"
                     icon="el-icon-edit-outline"
                     round
                     @click="showDialog(row)">
            编辑
          </el-button>
          <el-button type="danger"
                     @click="deleteUser(row.id)"
                     icon="el-icon-delete"
                     round>
            删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="block">
      <el-pagination @size-change="changeSize"
                     @current-change="changePage"
                     :current-page="userQuery.pageNum"
                     :page-sizes="[5, 10, 15, 20]"
                     :page-size="userQuery.pageSize"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="total">
      </el-pagination>
    </div>

    <el-dialog :title="dialogobj.title"
               width="700px"
               :visible.sync="dialogobj.visiable">
      <el-form :model="dialogobj.user"
               :inline="true"
               label-width="90px"
               ref="userForm"
               :rules="userRules"
               style=" margin-left:50px;">
        <el-form-item label="工号："
                      prop="workerNum">
          <el-input v-model.trim="dialogobj.user.workerNum"></el-input>
        </el-form-item>
        <el-form-item label="性别："
                      prop="sex">
          <el-radio-group v-model.trim="dialogobj.user.sex">
            <el-radio :label="0">男</el-radio>
            <el-radio :label="1">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="用户名："
                      prop="username">
          <el-input v-model.trim="dialogobj.user.username"></el-input>
        </el-form-item>
        <el-form-item label="密码："
                      prop="password"
                      v-if="dialogobj.user.id==null">
          <el-input v-model.trim="dialogobj.user.password"
                    show-password></el-input>
        </el-form-item>
        <el-form-item label="邮箱："
                      prop="email">
          <el-input v-model.trim="dialogobj.user.email"></el-input>
        </el-form-item>
        <el-form-item label="电话："
                      prop="phone">
          <el-input v-model.trim.number="dialogobj.user.phone"></el-input>
        </el-form-item>
        <el-form-item label="生日："
                      style="width:100%">
          <el-date-picker v-model="dialogobj.user.birthday"
                          type="date"
                          placeholder="请选择生日" />
        </el-form-item>
        <el-form-item label="部门："
                      prop="departmentId">
          <el-select v-model="dialogobj.user.departmentId"
                     placeholder="请选择">
            <el-option v-for="dep in depList"
                       :key="dep.id"
                       :disabled="dep.state==0"
                       :label="dep.name"
                       :value="dep.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="职位："
                      prop="positionId">
          <el-select v-model="dialogobj.user.positionId"
                     placeholder="请选择"
                     no-data-text="选择部门以获取职位信息">
            <el-option v-for="pos in posList"
                       :key="pos.id"
                       :disabled="pos.state==0"
                       :label="pos.name"
                       :value="pos.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="角色："
                      prop="roleIds">
          <el-select v-model="dialogobj.user.roleIds"
                     placeholder="请选择"
                     multiple>
            <el-option v-for="role in roleList"
                       :key="role.id"
                       :label="role.name"
                       :value="role.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="hideDialog">取 消</el-button>
        <el-button type="primary"
                   @click="formHandler">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { companyFilter, depFilter, posFilter } from '@/filters'
import { getUserList, deleteUserById, addUser, updateUser, queryUserByWorkerNum, queryUserByUsername } from '@/api/umsUser'
import { getDep } from '@/api/dmsDepartment'
import { getPos } from '@/api/pmsPostion'
import { getRoles } from '@/api/rmsRole'
export default {
  filters: {
    companyFilter,
    // roleFilter,
    depFilter,
    posFilter,
    userStateFilter (state) {
      const stateMap = ['demo', '空闲', '忙碌', '已离职']
      return stateMap[state]
    },
    stateTagFilter (state) {
      const stateMap = ['demo', 'success', 'danger', 'info']
      return stateMap[state]
    },
    sexFilter (sex) {
      const sexMap = {
        '0': '男',
        '1': '女'
      }
      return sexMap[sex]
    },
  },
  data () {
    //工号校验规则
    let validateWorkNum = (rule, value, callback) => {
      queryUserByWorkerNum({ workerNum: value, id: this.dialogobj.user.id }).then(res => {
        if (res.data) {
          callback([new Error('该工号已存在')])
        } else {
          callback();
        }
      })
    }
    //用户名校验规则
    let validateUsername = (rule, value, callback) => {
      queryUserByUsername({ username: value, id: this.dialogobj.user.id }).then(res => {
        if (res.data) {
          callback([new Error('该用户名已被占用')]);
        } else {
          callback();
        }
      })
    }
    return {
      userQuery: {
        example: {
          workerNum: undefined,
          username: undefined,
        },
        pageSize: 10,
        pageNum: 1
      },

      userList: null,
      depList: null,
      posList: null,
      roleList: null,

      userRules: {
        workerNum: [
          { required: true, message: "请输入八位工号", trigger: "blur" },
          { pattern: /^[A-Z]{2}[0-9]{6}$/, message: '请输入正确的工号', trigger: "blur" },
          { validator: validateWorkNum, trigger: "blur" },
        ],
        sex: [
          { required: true, message: "请选择性别", trigger: "blur" }
        ],
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 4, max: 16, message: '用户名长度在 4 到 16 个字符', trigger: 'blur' },
          { pattern: /^[a-zA-Z0-9_-]{4,16}$/, message: '只能由字母、数字、"_"、"-"组成', trigger: "blur" },
          { validator: validateUsername, trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' },
          { pattern: /^(?=.*\d)(?=.*[a-zA-Z]).{6,20}$/, message: '密码至少包含一个字母和一个数字', trigger: "blur" },
        ],
        phone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { pattern: /^[0-9]{11}$/, message: '手机号为11为数字', trigger: 'blur' },
          { pattern: /^((13[0-9])|(17[0-1,6-8])|(15[^4,\\D])|(18[0-9]))\d{8}$/, message: '请输入正确的手机号', trigger: "blur" },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { pattern: /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/, message: '请输入正确的邮箱', trigger: "blur" },
        ],
        departmentId: [
          { required: true, message: "请选择部门", trigger: "blur" },
        ],
        positionId: [
          { required: true, message: "请选择职位", trigger: "blur" },
        ],
        roleIds: [
          { required: true, message: "请选择角色", trigger: "blur" },
        ],
      },

      listLoading: true,
      total: 0,
      dialogobj: {
        title: '',
        isAdd: true,
        visiable: false,
        user: {}
      },
      tablefilters: {
        depFilters: null,
        posFilters: null
      }
    }
  },
  created () {
    this.init()
  },
  methods: {
    init () {//初始化页面
      this.fetchUser()
      this.fetchDep()
      this.fetchRole()
    },
    fetchUser () {//获取用户数据
      this.listLoading = true
      getUserList(this.userQuery).then(res => {
        const listPage = res.data
        this.userList = listPage.records
        this.total = listPage.total
        this.listLoading = false
      })
    },
    fetchDep () {//获取部门数据
      getDep().then(res => {
        this.depList = res.data
      })
    },
    fetchPos (params) {//获取职位数据
      if (params.ids) {
        getPos(params).then(res => {
          this.posList = res.data
        })
      }
    },
    fetchRole () {//获取角色数据
      getRoles().then(res => {
        this.roleList = res.data.records
      })
    },
    deleteUser (id) {//删除用户
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteUserById(id).then(response => {
          if (response.code == 20000) {
            this.fetchUser()
            this.$message({
              type: 'success',
              message: response.message
            })
          }
        })
      }).catch(() => { })
    },
    changeSize (size) {//更改每页呈现数据
      this.userQuery.pageSize = size
      this.userQuery.pageNum = Math.min(Math.ceil(this.total / size), this.userQuery.pageNum)
      this.fetchUser()
    },
    changePage (num) {//换页
      this.userQuery.pageNum = num
      this.fetchUser()
    },
    reset () {//重置搜索框内容和表格内容
      this.userQuery.example.workerNum = null
      this.userQuery.example.username = null
      this.fetchUser()
    },
    showDialog (user) {//显示对话框
      if (user == null) {
        this.dialogobj = { ...this.dialogobj, title: '添加用户', isAdd: true, user: { sex: 0 }, visiable: true }
      } else {
        this.dialogobj = { ...this.dialogobj, title: '修改用户', isAdd: false, user, visiable: true }
      }
    },
    formHandler () {//新增或修改用户信息
      this.$refs.userForm.validate(valid => {
        if (valid) {
          if (this.dialogobj.isAdd) {
            addUser(this.dialogobj.user).then(res => {
              if (res.code == 200) {
                this.fetchUser()
                this.$message({
                  type: 'success',
                  message: res.message
                })
                this.hideDialog()
              } else {
                this.$message({
                  type: 'error',
                  message: '未知错误'
                })
              }
            })
          } else {
            this.dialogobj.user.password = null //下面的接口不支持修改密码
            updateUser(this.dialogobj.user).then(res => {
              if (res.code == 200) {
                this.fetchUser()
                this.$message({
                  type: 'success',
                  message: res.message
                })
                this.hideDialog()
              } else {
                this.$message({
                  type: 'error',
                  message: '未知错误'
                })
              }
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    hideDialog () {
      this.$refs.userForm.clearValidate()
      this.dialogobj.visiable = false
    },
    getRoleName (id) {
      for (let role of this.roleList) {
        if (role.id == id) {
          return role.name
        }
      }
      return ''
    }
  },
  watch: {
    'dialogobj.user.departmentId' () {
      let posIds
      for (let dep of this.depList) {
        if (dep.id == this.dialogobj.user.departmentId) {
          posIds = dep.positionIds
          break
        }
      }
      this.fetchPos({ ids: posIds })
    },
    'dialogobj.visiable' (val) {
      if (!val) {
        this.$refs.userForm.clearValidate()
      }
    }
  }
}
</script>
